package com.disruptor.sample._08complex01.producer;

import com.disruptor.sample._07advance.dto.Trade;
import com.lmax.disruptor.EventTranslator;
import com.lmax.disruptor.dsl.Disruptor;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class TradePublisher implements Runnable {

  Disruptor<Trade> disruptor;

  private CountDownLatch latch;

  // 模拟百万次交易的发生
  private static int LOOP = 10;

  public TradePublisher(CountDownLatch latch, Disruptor<Trade> disruptor) {
    this.disruptor = disruptor;
    this.latch = latch;
  }

  @Override
  public void run() {
    TradeEventTranslator tradeTransloator = new TradeEventTranslator();
    for (int i = 0; i < LOOP; i++) {
      disruptor.publishEvent(tradeTransloator);
    }
    latch.countDown();
  }

}

class TradeEventTranslator implements EventTranslator<Trade> {

  private Random random = new Random();

  @Override
  public void translateTo(Trade event, long sequence) {
    this.generateTrade(event);
  }

  private Trade generateTrade(Trade trade) {
    trade.setPrice(random.nextDouble() * 9999);
    return trade;
  }

}
